<?php 
namespace Service;
use \Util\SyncFile;


class Gmess
{	
	/**
	 * 素材同步方法
	 * @param  array $gmesses   [服务器上的news素材]
	 * @param  int   $wechat_id [所属公众号]
	 * @return boolean
	 */
	public static function syncGmess($gmesses,$wechat_id)
	{	
		foreach ($gmesses as $key => $news_item) {
			//p($news_item);die;
			foreach ($news_item['content']['news_item'] as $k => $news) {
				
				$news['media_id']=$news_item['media_id'];
				$news['update_time']=$news_item['content']['update_time'];
				$news['create_time']=$news_item['content']['create_time'];
				$news['wei_url']=$news['url'];
				$news['wechat_id']=$wechat_id;
				$news['catimg']=SyncFile::syncFile('gmess',$news['thumb_url'],'jpg');
				$news['content']=str_replace('data-src','src',SyncFile::syncImg('gmess',$news['content']));

				$exist=self::checkExist($news_item['media_id'],$news['title']);
				
				if(!$exist){
					db('gmess_page')->add($news);
				}else{
					db('gmess_page')->where(['id'=>$exist['id']])->save($news);
				}
			}
		}
	}


	/**
	 * 检测是否存在该素材
	 * @author zsoner zsoner@wsxhr.com
	 * @date   2016-08-12
	 * @param  string     $media_id 微信对应的素材media_id
	 * @param  title      $title    素材标题
	 * @return mixed 	  			本地对应的id或者null
	 */
	public static function checkExist($media_id,$title)
	{
		return db('gmess_page')->where(['media_id'=>$media_id,'title'=>$title])->find();
	}

	
}

?>